package com.shouxin.attendance.utils;

import android.os.SystemClock;

import com.shouxin.attendance.database.DBHelper;
import com.shouxin.attendance.database.model.Baby;
import com.shouxin.attendance.database.model.PushData;
import com.shouxin.attendance.database.model.SwipeCardHistory;
import com.shouxin.attendance.service.BackgroundService;

import org.apache.log4j.Logger;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public final class HandleSwipeCard {

	private static final Logger logger = Logger.getLogger(HandleSwipeCard.class);

	private BlockingQueue<SwipeCard> linkedQueue = new LinkedBlockingQueue<>();

	private HandleSwipeCard() {
		new Thread(new SwipeCardTask()).start();
	}

	public static HandleSwipeCard get() {
		return Instance.instance;
	}

    public void addSwipeInfo(Baby baby, String cardNumber, long time, int state) {
        linkedQueue.offer(new SwipeCard(baby, cardNumber, state, time));
	}

	private static class Instance {

		static HandleSwipeCard instance = new HandleSwipeCard();
	}

	private class SwipeCardTask implements Runnable {

		@Override
		public void run() {
			while (true) {
				try {
					SwipeCard swipeCard = linkedQueue.take();

					Baby baby = swipeCard.baby;
					String[] dateTime = TimeUtils.getTimeString(swipeCard.time).split(" ");
					String sendDate = dateTime[0];
					String sendTime = dateTime[1];

					SwipeCardHistory history = new SwipeCardHistory();
					history.setBaby(baby);
					history.setClassId(baby.getClassId());
					history.setSendDate(sendDate);
					history.setSendTime(sendTime);
					history.setTimeStamp(swipeCard.time);
					history.setStatus(swipeCard.state);
					DBHelper.getInstance().getSwipeCardHistoryDao().insert(history);

					PushData pushData = new PushData();
					pushData.setBaby(baby);
					pushData.setExceptionCode(0);
					pushData.setSendTime(swipeCard.time / 1000);
					pushData.setStatus(swipeCard.state);
					BackgroundService.getInstance().addPushData(pushData);

					SystemClock.sleep(1000);
				} catch (InterruptedException e) {
					logger.error("SwipeCardTask Exception", e);
				}
			}
		}
	}

	private class SwipeCard {

        private final Baby baby;

        private final String cardNumber;

        private final int state;

        private final long time;

        SwipeCard(Baby baby, String cardNumber, int state, long time) {
            this.baby = baby;
			this.cardNumber = cardNumber;
			this.state = state;
			this.time = time;
		}
	}
}
